package com.appbee.user.server.dao;

import javax.inject.Inject;
import javax.inject.Provider;

import com.appbee.user.server.model.WebUser;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;

public class AccessControl
{
	private final UserService userService;
	private Provider<MemberDAO> memberDaoProvider;
	private WebUser webUser;

	@Inject
	public AccessControl(UserService userService,
			Provider<MemberDAO> memberDaoProvider)
	{
		super();
		this.userService = userService;
		this.memberDaoProvider = memberDaoProvider;
	}

	public String getCurrentUserEmail()
	{
		User currentUser = userService.getCurrentUser();
		return currentUser == null ? "" : currentUser.getEmail();
	}

	public WebUser getCurrentUser()
	{
		if (webUser == null)
		{
			webUser = new WebUser();
			User user = userService.getCurrentUser();
			if (user != null)
			{
				webUser.setEmail(user.getEmail());
				webUser.setNickName(user.getNickname());
				webUser.setAdmin(userService.isUserAdmin());
				webUser.setMember(memberDaoProvider.get().findByEmail(
						user.getEmail()));

			}
		}
		return webUser;
	}

	public WebUser getCurrentUser(String destinationURL)
	{
		WebUser u = getCurrentUser();
		User user = userService.getCurrentUser();
		if (user != null)
		{
			u.setLoginOrOutUrl(userService.createLogoutURL(destinationURL));
		}
		else
		{
			u.setLoginOrOutUrl(userService.createLoginURL(destinationURL));
		}
		return u;
	}

	public void assertUserIsAdmin()
	{
		if (!userService.isUserAdmin())
			throw new RuntimeException("User not admin");
	}

	public void assertIsMemberOrAdmin()
	{
		if (!getCurrentUser().getAdmin()
				&& getCurrentUser().getMember() == null)
		{
			throw new RuntimeException("User not member or admin");
		}
	}

}
